import { Asset, AudioClip, JsonAsset, Prefab, __private, loader, resources, sys } from "cc";
import { LoadCtrl } from "../Ctrl/LoadCtrl";
import { Unit } from "../Entity/Unit";
import Dialog from "../UI/Dialog/Dialog";
import { Global, UnitType } from "../Util/Global";
import { Tools } from "../Util/Tools";

export default class AssetsMgr {

    static prefabMap: Map<string, Prefab> = new Map();

    static unitPrefabMap: Map<UnitType, Map<string, Prefab>> = new Map();

    // static unitIconPrefabMap: Map<UnitType, Prefab> = new Map();//icon

    static dialogPrefabMap: Map<string, Prefab> = new Map();

    static plistPrefabMap: Map<string, Prefab> = new Map();

    static async Init() {
        // let res_eff = await LoadCtrl.loadBundleAllRes("sounds/effect", AudioClip)
        // SoundCtrl.setEff(res_eff);
        // let res_music = await LoadCtrl.loadBundleAllRes("sounds/music", AudioClip)
        // SoundCtrl.setMusic(res_music);

        //加载prefabs下的所有资源
        let ps1 = await LoadCtrl.loadBaseAllRes("prefabs", Prefab);
        for (let p of ps1) {
            this.prefabMap.set(p.name, p);
            let unit: Unit = p.data.getComponent(Unit);

            if (unit) {
                let pArr = this.unitPrefabMap.get(unit.unitType) || new Map();
                pArr.set(p.name, p);
                this.unitPrefabMap.set(unit.unitType, pArr);
            }
        }

        this.prefabMap.forEach((v, k) => {
            let nameCb = k.split("_");
            let typ = nameCb.splice(nameCb.length - 1, 1)[0];
            let name = nameCb.join('_')
            if (typ == "Dialog") {
                let d = v.data.getComponent(Dialog);
                let name = Object.getPrototypeOf(d)["__classname__"]
                this.dialogPrefabMap.set(name, v)
            }
            else if (typ == 'Plist') {
                this.plistPrefabMap.set(k, v);
            }
        });

        let configs = await LoadCtrl.loadBaseAllRes('configs', JsonAsset)
        Global.config = {};
        configs.forEach(cfg => {
            let kv = cfg.json;
            Object.keys(kv).forEach((k) => {
                Global.config[k] = kv[k];
            })
        })
    }

    /**加载远程资源 */
    static getRes<T extends Asset>(path: string, type: __private.__types_globals__Constructor<T>, succeed?: (res: T) => void) {
        let _path = path.split("/");
        let resName = _path[_path.length - 1];
        if (_path[0] === 'prefabs') {
            let res: any = this.prefabMap.get(resName);
            if (res) {
                succeed && succeed(res);
            }

            return res;
        }

        return LoadCtrl.loadBundleRes(path, type, succeed);
    }

    static getUnitPrefab(type: UnitType, name?: string) {
        let typPool = this.unitPrefabMap.get(type);
        if (typPool) {
            let _name = name || Tools.getEnumName(UnitType, type);
            return typPool.get(_name);
        }

        return null;
    }

}